# -*- coding: utf-8 -*-
"""
TG框架组件 - TgFrame
框架容器组件，提供可见边框的容器
"""
from PySide6.QtWidgets import QFrame
from PySide6.QtCore import Qt
from ...style_manager import StyleManager
from ..layouts.vbox_layout import TgVBoxLayout
from ..layouts.hbox_layout import TgHBoxLayout


class TgFrame(QFrame):
    """TG框架"""
    
    def __init__(self, frame_style='panel', layout_type=None, parent=None, layout_margins='medium', layout_spacing='medium'):
        super().__init__(parent)
        # 初始化TG组件属性
        self._component_name = self.__class__.__name__
        self._is_initialized = False
        self._style_applied = False
        self._theme = 'default'
        self._size_hint = 'medium'
        self._layout = None
        
        # 设置组件特定属性
        self.frame_style = frame_style
        
        # 初始化组件
        self.initialize()

        # 如果提供了布局类型，则创建并设置布局
        if layout_type:
            if layout_type == 'vbox':
                self._layout = TgVBoxLayout(self, margins=layout_margins, spacing=layout_spacing)
            elif layout_type == 'hbox':
                self._layout = TgHBoxLayout(self, margins=layout_margins, spacing=layout_spacing)
            else:
                raise ValueError(f"Unsupported layout_type: {layout_type}")
    
    @property
    def component_name(self):
        """获取组件名称"""
        return self._component_name
    
    @property
    def is_initialized(self):
        """检查组件是否已初始化"""
        return self._is_initialized
    
    @property
    def style_applied(self):
        """检查样式是否已应用"""
        return self._style_applied
    
    def setup_ui(self):
        """设置用户界面"""
        if self.frame_style == 'panel':
            self.setFrameStyle(QFrame.Shape.StyledPanel)
        elif self.frame_style == 'box':
            self.setFrameStyle(QFrame.Shape.Box)
        elif self.frame_style == 'line':
            self.setFrameStyle(QFrame.Shape.HLine)
    
    def apply_style(self):
        """应用样式"""
        self.setStyleSheet(f"""
            QFrame {{
                border: 1px solid {StyleManager.COLORS['border']};
                border-radius: {StyleManager.BORDER_RADIUS['small']};
                background-color: {StyleManager.COLORS['background']};
                padding: {StyleManager.SPACING['sm']};
            }}
        """)
        self._style_applied = True
    
    def initialize(self):
        """初始化组件"""
        if not self._is_initialized:
            self.setup_ui()
            self.apply_style()
            self._is_initialized = True
            self._style_applied = True

    def addWidget(self, widget, stretch=0, alignment=None):
        """向布局中添加一个组件"""
        if self._layout:
            if alignment:
                self._layout.addWidget(widget, stretch, alignment)
            else:
                self._layout.addWidget(widget, stretch)
        else:
            raise RuntimeError("No layout has been set for this TgFrame.")